package com.d3works.apps.bankpayment.service.invoice.payment;

import com.d3works.apps.account.db.InvoicePayment;
import com.d3works.apps.account.db.PaymentMode;
import com.d3works.apps.account.db.repo.InvoicePaymentRepository;
import com.d3works.apps.account.service.invoice.InvoiceService;
import com.d3works.apps.account.service.invoice.InvoiceTermService;
import com.d3works.apps.account.service.payment.invoice.payment.InvoicePaymentCreateServiceImpl;
import com.d3works.apps.account.service.payment.invoice.payment.InvoicePaymentToolService;
import com.d3works.apps.account.service.payment.invoice.payment.InvoiceTermPaymentService;
import com.d3works.apps.bankpayment.service.bankorder.BankOrderMergeService;
import com.d3works.apps.base.db.BankDetails;
import com.d3works.apps.base.service.CurrencyService;
import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.exception.D3worksException;
import com.d3works.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import com.google.inject.servlet.RequestScoped;
import java.time.LocalDate;
import java.util.List;

@RequestScoped
public class InvoicePaymentCreateServiceBankPayImpl extends InvoicePaymentCreateServiceImpl {

  @Inject
  public InvoicePaymentCreateServiceBankPayImpl(
      InvoicePaymentRepository invoicePaymentRepository,
      InvoicePaymentToolService invoicePaymentToolService,
      CurrencyService currencyService,
      AppBaseService appBaseService,
      InvoiceTermPaymentService invoiceTermPaymentService,
      InvoiceTermService invoiceTermService,
      InvoiceService invoiceService) {

    super(
        invoicePaymentRepository,
        invoicePaymentToolService,
        currencyService,
        appBaseService,
        invoiceTermPaymentService,
        invoiceTermService,
        invoiceService);
  }

  @Override
  @Transactional(rollbackOn = {Exception.class})
  public List<InvoicePayment> createMassInvoicePayment(
      List<Long> invoiceList,
      PaymentMode paymentMode,
      BankDetails companyBankDetails,
      LocalDate paymentDate,
      LocalDate bankDepositDate,
      String chequeNumber)
      throws D3worksException {

    List<InvoicePayment> invoicePaymentList =
        super.createMassInvoicePayment(
            invoiceList,
            paymentMode,
            companyBankDetails,
            paymentDate,
            bankDepositDate,
            chequeNumber);

    if (!appBaseService.isApp("bank-payment")) {
      return invoicePaymentList;
    }

    if (invoicePaymentList.isEmpty()) {
      return invoicePaymentList;
    }

    if (paymentMode.getGenerateBankOrder()) {
      Beans.get(BankOrderMergeService.class).mergeFromInvoicePayments(invoicePaymentList);
    }
    return invoicePaymentList;
  }
}
